/**
 * * @author Eric Jahn * Course: Object Oriented Programming * Final Project *
 * Due Date: August 3, 2012
 */
package oop.chat.data;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import oop.chat.user.UserAccount;

/**
 * database class to store all messages in a database *
 * @author Eric Jahn
 */
public class ConverseDB
{
	//hash algorithm
	private static final String HASH_ALGORITHM = "SHA-256";	
	
    private Map<String, UserAccount> userAccounts;
    private List messageLogs;

	/**
	 * constructor
	 */
    public ConverseDB()
    {
        this.userAccounts = (Map<String, UserAccount>) Collections.synchronizedMap(new HashMap<String, UserAccount>());
//      this.messageLogs = (List) Collections.synchronizedList(new ArrayList());   
    }
    
    /**
     * Add UserAccount to database, replaces UserAccount if it already existed
     * @param	user		UserAccount
     */
    public void addUserAccount(UserAccount user)
    {
        this.userAccounts.put(user.getContactInfo().getPID(), user);
    }

	/**
	 * gets the user account
	 * @param	PID			String
	 * @return	UserAccount
	 */
    public final UserAccount getUserAccount(String PID)
    {
        return this.userAccounts.get(PID);
    }
    
    /**
     * Add MessageLog to database with user PID as key, 
     * replaces MessageLog if it already existed
     * @param user
     * @param log 
     */
    public void addMessageLog(MessageLog log)
    {
//        this.messageLogs.add(log);
    }

    public String listUserAccounts()
    {
        StringBuffer userList = new StringBuffer();
        Set entries = userAccounts.entrySet();
        Iterator iter = entries.iterator();
        while (iter.hasNext())
        {
            Map.Entry entry = (Map.Entry) iter.next();
            userList.append("User:  ");
            userList.append(entry.getKey());
            userList.append(" ");
            userList.append(entry.getValue());
            userList.append("\n");
        }
        return userList.toString();
    }
	
	/**
	 * encryptes the password with a hash algorithm
	 * @param	password			String
	 * @return	hashed password		String
	 */
	public static String md5Password(String password)
	{
		StringBuilder hashedPassword = new StringBuilder();
		//obtain instance of the algorithm
		MessageDigest messageDigest; 
		try {
			messageDigest = MessageDigest.getInstance(ConverseDB.HASH_ALGORITHM);
			messageDigest.update(password.getBytes());
		
			byte byteData[] = messageDigest.digest();
			//convert the byte to hex format
			for (byte b : byteData) {
				hashedPassword.append(String.format("%02x", b));
			}
		}
		catch(NoSuchAlgorithmException ex)
		{
			ex.printStackTrace();
		}
		
		return hashedPassword.toString();
	}
	
	/**
	 * read in the user password from a file
	 * @param	PID				String
	 * @return	password		String
	 */
	public static String getPasswordFromFile(String PID)
	{
		String password = "";
		String filename = PID + ".txt";
		
		try
		{
			File file = new File(filename);
			if(file.exists())
			{
				FileInputStream fileInputStream = new FileInputStream(file);
				DataInputStream inputStream = new DataInputStream(fileInputStream);
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				//read in the password
				password = bufferedReader.readLine();
				//Close the input stream
				inputStream.close();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return password;
	}
}